-- || Created by Revelse

GamemodeManager = inherit(Singleton)

addEvent("requestGamemodeDetails",true)
addEvent("requestGamemodeJoin",true)

function GamemodeManager:constructor()
	self.m_Gamemodes = {}
	
	addEventHandler("requestGamemodeDetails", root, bind(self.sendGamemodeDetails,self))
	addEventHandler("requestGamemodeJoin", root, bind(self.sendPlayerInGamemode,self))
end

function GamemodeManager:ready()
	
	print("Loading Gamemodes...")
	
	-- Deathmatch
	self.m_Deathmatch = self:createGamemode("Deathmatch")
	self.m_Deathmatch:addRoom(DeathmatchRoom:new())
	self.m_Deathmatch:addRoom(DeathmatchRoom:new())
	
	for _, room in ipairs( self.m_Deathmatch:getRooms() ) do
		room:setMaxPlayers(8)
	end
	
	-- Deathmatch ( Desert Eagle Only )
	self.m_Deagle = self:createGamemode("Deagle")
	self.m_Deagle:addRoom(DeagleRoom:new())
	self.m_Deagle:addRoom(DeagleRoom:new())
	
	for _, room in ipairs( self.m_Deagle:getRooms() ) do
		room:setMaxPlayers(6)
	end
	
	-- Duell-Rooms

	self.m_Duell = self:createGamemode("Duell")
	self.m_Duell:addRoom(DuellRoom:new())
	self.m_Duell:addRoom(DuellRoom:new())
	self.m_Duell:addRoom(DuellRoom:new())
	self.m_Duell:addRoom(DuellRoom:new())
	
	for _, room in ipairs( self.m_Duell:getRooms() ) do
		room:setMaxPlayers(2)
	end	
	
end

function GamemodeManager:sendPlayerInGamemode(gamemode,room,player)
	if player then client = player end
	if self:getGamemodeByName(gamemode):getRooms()[room]:addPlayer(client) then
		
	end
end

function GamemodeManager:sendGamemodeDetails(player)
	local client = client
	if not client then
		client = player
	end
	client:triggerEvent("reciveGamemodeDetails",self:getGamemodeDetails())
end

function GamemodeManager:getGamemodeDetails()
	local details = {}
	local i = 1
	for name, gm in pairs ( self.m_Gamemodes ) do
		details[i] = {
		lobbyName = name,
		rooms = {},
		}
		for key, value in ipairs ( gm:getRooms() ) do
			details[i].rooms[key] = {
				minPlayers     = value:getMinPlayers(),
				maxPlayers     = value:getMaxPlayers(),
				currentPlayers = #value:getPlayers(),
			}
		end
		i = i + 1
	end
	return details
end

function GamemodeManager:getGamemodes() return self.m_Gamemodes end

function GamemodeManager:getGamemodeByName(name)
	return self.m_Gamemodes[name] or self:createGamemode(name)
end

function GamemodeManager:createGamemode(name)
	self.m_Gamemodes[name] = Gamemode:new(name)
	print((" Successfully created %s - Gamemode"):format(name))
	return self.m_Gamemodes[name]
end


-- ** TEST **
		

